package com.buka.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buka.api.OrderApi;
import com.buka.common.BizCodeEnum;
import com.buka.config.MQConfig;
import com.buka.constants.Constants;
import com.buka.dao.ProductDao;
import com.buka.dao.ProductTaskDao;
import com.buka.entity.Product;
import com.buka.entity.ProductTask;
import com.buka.message.ProductMessage;
import com.buka.request.LockProductRequest;
import com.buka.request.OrderItemRequest;
import com.buka.service.ProductTaskService;
import com.buka.util.JsonData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (ProductTask)表服务实现类
 *
 * @author makejava
 * @since 2025-08-13 14:07:05
 */
@Service("productTaskService")
public class ProductTaskServiceImpl extends ServiceImpl<ProductTaskDao, ProductTask> implements ProductTaskService {

    @Resource
    ProductDao productDao;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    MQConfig mqConfig;

    @Resource
    OrderApi orderApi;

    /**
     * 1.校验商品信息（商品是否存在、库存是否大于购买量）
     * 2.扣减库存
     * 3.生成锁定记录
     * 4.向MQ发送消息
     *
     * @param request 订单信息（订单编号，订单中的商品ID与数量）
     * @return
     */
    @Override
    @Transactional
    public JsonData reduce(LockProductRequest request) {
        //订单中商品明细
        List<OrderItemRequest> orderItemList = request.getOrderItemRequest();
        //订单详情转成map
        Map<Long, Integer> proBuyNumMap = orderItemList.stream()
                .collect(Collectors.toMap(OrderItemRequest::getProductId, OrderItemRequest::getBuyNum));

        //提取订单中的商品id集合
        List<Long> productIdList = orderItemList.stream().map(OrderItemRequest::getProductId).collect(Collectors.toList());
        //使用商品id集合批量查询
        LambdaQueryWrapper<Product> proQuery = Wrappers.lambdaQuery(Product.class);
        proQuery.in(Product::getId, productIdList);
        List<Product> productList = productDao.selectList(proQuery);

        //校验商品是否存在
        if (productList.size() != productIdList.size()) {
            return JsonData.buildResult(BizCodeEnum.NOT_PRODUCT);
        }

        for (Product product : productList) {
            //每件商品购买数量
            Integer buyNum = proBuyNumMap.get(product.getId());
            //锁定库存数量
            int update = productDao.lockStock(buyNum, product.getId());
            if (update < 1) {
                return JsonData.buildResult(BizCodeEnum.REDUCE_ERR);
            }
            //库存锁定记录
            ProductTask productTask = new ProductTask();
            productTask.setProductId(product.getId());
            productTask.setBuyNum(buyNum);
            productTask.setProductName(product.getTitle());
            //锁定状态
            productTask.setLockState(Constants.StockTaskStateEnum.LOCK.name());
            productTask.setOutTradeNo(request.getOrderOutTradeNo());
            productTask.setCreateTime(new Date());
            //保存记录
            save(productTask);

            //发送延时消息
            ProductMessage productMessage = new ProductMessage();
            productMessage.setOutTradeNo(request.getOrderOutTradeNo());
            productMessage.setTaskId(productTask.getId());
            rabbitTemplate.convertAndSend(mqConfig.getEventExchange(),
                    mqConfig.getStockReleaseDelayRoutingKey(),
                    productMessage);
        }
        return JsonData.buildSuccess();
    }


    /**
     * 根据订单状态回滚库存
     */
    @Override
    public boolean releaseStock(ProductMessage productMessage) {
        //先判断锁定表的记录是否存在，如果记录不在了，说明订单已经销毁了，不需要重新放会队列。流程结束
        Long taskId = productMessage.getTaskId();
        ProductTask task = getById(taskId);
        if (null == task) {
            return true;
        }

        String lockState = task.getLockState();
        if (!lockState.equals(Constants.StockTaskStateEnum.LOCK.name())) {
            //如果库存已经是解锁状态，不需要继续执行解锁逻辑了
            return true;
        }

        //查询订单状态
        String outTradeNo = productMessage.getOutTradeNo();
        JsonData jsonData = orderApi.queryOrderState(outTradeNo);
        if (jsonData.getCode() != 0) {
            return false;
        }

        String orderStatus = (String) jsonData.getData();


        //判断订单状态
        if (Constants.OrderStatusEnum.PAY.name().equals(orderStatus)) {
            //订单已支付设置订单锁定表为完成状态
            task.setLockState(Constants.StockTaskStateEnum.FINISH.name());
            // 扣减库存 不需要扣减库存，库存应该是在发货的时候扣减，不应该是支付成功时扣减

        } else if (Constants.OrderStatusEnum.CANCEL.name().equals(orderStatus)) {
            //取消状态
            task.setLockState(Constants.StockTaskStateEnum.CANCEL.name());
            //释放库存，修改库存表中的锁定库存数量，其值减去购买数量
            int i = productDao.releaseStock(task.getBuyNum(), task.getProductId());
            return i > 0;
        } else {
            return false;
        }

        //修改库存锁定表的状态
        updateById(task);

        return true;
    }


}

